package com.jsh.erp.utils;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.NoCustomContextException;
import com.itextpdf.tool.xml.Tag;
import com.itextpdf.tool.xml.WorkerContext;
import com.itextpdf.tool.xml.html.HTML;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ImageTagProcessor extends com.itextpdf.tool.xml.html.Image {
	public List end(final WorkerContext ctx, final Tag tag, final List currentContent) {
		final Map<String, String> attributes = tag.getAttributes();
		String src = attributes.get(HTML.Attribute.SRC);
		List elements = new ArrayList(1);
		if (null != src && src.length() > 0) {
			Image img = null;
			if (src.startsWith("data:image/")) {
				final String base64Data = src.substring(src.indexOf(",") + 1);

				try {
					img = Image.getInstance(Base64.decode(base64Data));
				} catch (BadElementException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (img != null) {

					HtmlPipelineContext htmlPipelineContext = null;
					try {
						htmlPipelineContext = getHtmlPipelineContext(ctx);
					} catch (NoCustomContextException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					elements.add(getCssAppliers().apply(
							new Chunk((Image) getCssAppliers().apply(img, tag, htmlPipelineContext),
									0, 0, true),
							tag, htmlPipelineContext));

				}
			}
			if (img == null) {
				elements = super.end(ctx, tag, currentContent);
			}
		}
		return elements;
	}
}
